jQuery(function ($) {
    //创建DOM
    var
        quickHTML = document.querySelector("div.quick_link_mian"),
        quickShell = $(document.createElement('div')).html(quickHTML).addClass('quick_links_wrap'),
        quickLinks = quickShell.find('.quick_links');
    quickPanel = quickLinks.next();
    quickShell.appendTo('.mui-mbar-tabs');

    //具体数据操作
    var
        quickPopXHR,
        popTmpl = '<a href="javascript:;" class="ibar_closebtn" title="关闭"></a><div class="ibar_plugin_title"><h3><%=title%></h3></div><div class="pop_panel"><%=content%></div><div class="arrow"><i></i></div><div class="fix_bg"></div>',
        quickPop = quickShell.find('#quick_links_pop'),
        quickDataFns = {
            //
            history_list: {
                title: '状态指示',
                content: '<div class="ibar_plugin_content"><div class="ia-head-list"><a href="#" target="_blank" class="pl"><div class="num">10</div><div class="text">速度</div></a><a href="#" target="_blank" class="pl"><div class="num">264</div><div class="text">高度</div></a><a href="#" target="_blank" class="pl money"><div class="num">23</div><div class="text">姿态</div></a></div><div class="ga-expiredsoon"><div class="es-head">系统</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">通讯</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">发动机</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">INIT</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">地面</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">降落伞</div><div class="ia-none">-----</div></div><div class="ga-expiredsoon"><div class="es-head">能源</div><div class="ia-none">-----</div></div></div>',
                init: $.noop
            },
            mpbtn_histroy: {
                title: '实体列表',
                content: '<div class="ibar_plugin_content">' +
                    '<div class="panel panel-default">\n' +
                    '  <div class="panel-heading">共三个实体</div>\n' +
                    '  <div class="panel-body">\n' +
                    '<div class="input-group">\n' +
                    '  <span class="input-group-addon" id="basic-addon1">经度</span>\n' +
                    '  <input id="lng" type="text" class="form-control" placeholder="经度" aria-describedby="basic-addon1">\n' +
                    '</div>' +
                    '<div class="input-group">\n' +
                    '  <span class="input-group-addon" id="basic-addon1">纬度</span>\n' +
                    '  <input id="lat" type="text" class="form-control" placeholder="纬度" aria-describedby="basic-addon1">\n' +
                    '</div>' +
                    '<div class="input-group">\n' +
                    '  <span class="input-group-addon" id="basic-addon1">高度</span>\n' +
                    '  <input id="hig" type="text" class="form-control" placeholder="高度" aria-describedby="basic-addon1">\n' +
                    '</div>' +
                    '  </div>\n' +
                    '</div>' +

                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/导弹车-big.jpg" width="100%" height="100%" /></a><p class="price"><em>导弹车</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/daodanche.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/导弹-big.jpg" width="100%" height="100%" /></a><p class="price"><em>导弹</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/daodan.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/导弹井-big.jpg" width="100%" height="100%" /></a><p class="price"><em>导弹井</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/daodanjing.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/指挥中心-big.jpg" width="100%" height="100%" /></a><p class="price"><em>指挥中心</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/huiyishi.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/雷达-big.jpg" width="100%" height="100%" /></a><p class="price"><em>雷达</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/leida.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"><a href="#" class="pic"><img src="img/model/飞机-big.jpg" width="100%" height="100%" /></a><p class="price"><em>飞机</em></p><button type="button" class="btn btn-default" onclick="createModel(\'model/CesiumAir/Cesium_Air.gltf\')">添加</button></div></div>' +
                    '<div class="ibar-moudle-product"><div class="imp_item"></div></div>' +

                    '</div>',
                init: $.noop
            },
            mpbtn_wdsc: {
                title: '菜单三',
                content: '<div class="ibar_plugin_content"></div>',
                init: $.noop
            }
        };

    //showQuickPop
    var
        prevPopType,
        prevTrigger,
        doc = $(document),
        popDisplayed = false,
        hideQuickPop = function () {
            if (prevTrigger) {
                prevTrigger.removeClass('current');
            }
            popDisplayed = false;
            prevPopType = '';
            quickPop.hide();
            quickPop.animate({left: 280, queue: true});
        },
        showQuickPop = function (type) {
            if (quickPopXHR && quickPopXHR.abort) {
                quickPopXHR.abort();
            }
            if (type !== prevPopType) {
                var fn = quickDataFns[type];
                quickPop.html(ds.tmpl(popTmpl, fn));
                fn.init.call(this, fn);
            }
            doc.unbind('click.quick_links').one('click.quick_links', hideQuickPop);

            quickPop[0].className = 'quick_links_pop quick_' + type;
            popDisplayed = true;
            prevPopType = type;
            quickPop.show();
            quickPop.animate({left: 0, queue: true});
        };
    quickShell.bind('click.quick_links', function (e) {
        e.stopPropagation();
    });
    quickPop.delegate('a.ibar_closebtn', 'click', function () {
        quickPop.hide();
        quickPop.animate({left: 280, queue: true});
        if (prevTrigger) {
            prevTrigger.removeClass('current');
        }
    });

    //通用事件处理
    var
        view = $(window),
        quickLinkCollapsed = !!ds.getCookie('ql_collapse'),
        getHandlerType = function (className) {
            return className.replace(/current/g, '').replace(/\s+/, '');
        },
        showPopFn = function () {
            var type = getHandlerType(this.className);
            if (popDisplayed && type === prevPopType) {
                return hideQuickPop();
            }
            showQuickPop(this.className);
            if (prevTrigger) {
                prevTrigger.removeClass('current');
            }
            prevTrigger = $(this).addClass('current');
        },
        quickHandlers = {
            history_list: showPopFn,
            mpbtn_histroy: showPopFn,
            mpbtn_wdsc: showPopFn
        };
    quickShell.delegate('a', 'click', function (e) {
        var type = getHandlerType(this.className);
        if (type && quickHandlers[type]) {
            quickHandlers[type].call(this);
            e.preventDefault();
        }
    });

    //Return top
    var scrollTimer, resizeTimer, minWidth = 1350;

    function resizeHandler() {
        clearTimeout(scrollTimer);
        scrollTimer = setTimeout(checkScroll, 160);
    }

    function checkResize() {
        quickShell[view.width() > 1340 ? 'removeClass' : 'addClass']('quick_links_dockright');
    }

    function scrollHandler() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(checkResize, 160);
    }

    function checkScroll() {
        view.scrollTop() > 100 ? showReturnTop() : hideReturnTop();
    }

    function showReturnTop() {
        quickPanel.addClass('quick_links_allow_gotop');
    }

    function hideReturnTop() {
        quickPanel.removeClass('quick_links_allow_gotop');
    }

    view.bind('scroll.go_top', resizeHandler).bind('resize.quick_links', scrollHandler);
    quickLinkCollapsed && quickShell.addClass('quick_links_min');
    resizeHandler();
    scrollHandler();

    var scene = viewer.scene;
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    var modelId = '';

    scene.postRender.addEventListener(function () {
        var heading = scene.camera.heading;
        var x = -Cesium.Math.toDegrees(heading);
        var degrees = "rotate(" + x + "deg)";
        // console.log("heading->  "+heading + "     x--->"+x+"       degrees----->" + degrees)
        $("#compass").css("transform", degrees);
    });

    handler.setInputAction(function (movement) {

        var pick = viewer.scene.pick(movement.position);
        // console.log("========>" + pick.id.id);
        // modelId = pick.id.id;
        if (!(pick === undefined)) {
            modelId = pick.id.id;
        }


    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    handler.setInputAction(function (click) {
        console.log('中键单击事​​件：', click.position);
        console.log('中键单击事​​件：', modelId);

        viewer.entities.removeById(modelId);
    }, Cesium.ScreenSpaceEventType.MIDDLE_CLICK);
    handler.setInputAction(function (movement) {
        var cartesian = scene.camera.pickEllipsoid(movement.endPosition, ellipsoid);
        var ellipsoid = scene.globe.ellipsoid;
        if (cartesian) { //能获取，显示坐标
            var cartographic = ellipsoid.cartesianToCartographic(cartesian);
            var coords = '经度' + Cesium.Math.toDegrees(cartographic.longitude).toFixed(6) + ', ' + '纬度' + Cesium.Math.toDegrees(cartographic.latitude).toFixed(6) + '，' + '高度' + Math.ceil(viewer.camera.positionCartographic.height);
            // document.getElementByIdx_x_x('coords').innerHTML = coords; document.getElementByIdx_x_x('coords').style.display = '';
            // console.log("-->" + coords);

            $("#lng").val(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6));
            $("#lat").val(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6));
            $("#hig").val(Math.ceil(viewer.camera.positionCartographic.height));

            $("#lng_none").val(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6));
            $("#lat_none").val(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6));
            $("#hig_none").val(Math.ceil(viewer.camera.positionCartographic.height));
            // console.log($("#lng").val());

        } else { //不能获取不显示
            // document.getElementByIdx_x_x('coords').style.display = 'none';
            // console.log("-->" + 不能获取不显示);
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    var czml = [{
        "id": "document",
        "name": "CZML Geometries: Polyline",
        "version": "1.0"
    }, {
        "id": "blueLine",
        "name": "Glowing blue line on the surface",
        "polyline": {
            "positions": {
                "cartographicDegrees": [
                    100.980167, 39.771438, 1,
                    100.980493, 39.771058, 1
                ]
            },
            "material": {
                "polylineGlow": {
                    "color": {
                        "rgba": [100, 149, 237, 255]
                    },
                    "glowPower": 0.2,
                    "taperPower": 0.5
                }
            },
            "width": 10
        }
    }];
    var dataSourcePromise = Cesium.CzmlDataSource.load(czml);
    viewer.dataSources.add(dataSourcePromise);
    viewer.zoomTo(dataSourcePromise);


});
